#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <functional>
#include "Logger.hpp"
#include "InetAddr.hpp"

using callback_t = std::function<void(int socket, const std::string message, InetAddr inetaddr)>; // 不要设为引用
static const int gdefaultsockfd = -1;
class ChatServer
{
public:
    ChatServer(uint16_t port, callback_t func)
        : _sockfd(gdefaultsockfd), _port(port), _cb(func), _isrunning(false) 
    {
    }
    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //  把网络在文件系统中展开
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success: " << _sockfd;

        InetAddr local(_port);

        int n = bind(_sockfd, local.Addr(), local.Length());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success : " << _sockfd;
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 读取数据
            char buffer[1024];
            buffer[0] = 0; //  O(1) 清空数据
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len); // flag == 0 , 阻塞模式
            if (n > 0)
            {
                buffer[n] = 0;
                InetAddr clinetaddr(peer);
                LOG(LogLevel::DEBUG) << "get a client info# " << clinetaddr.Ip() << " - " << clinetaddr.Port() << ": " << buffer;

                std::string message = buffer;
                // 回调
                _cb(_sockfd, message, clinetaddr);
            }
        }
        _isrunning = false;
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~ChatServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip; // 不建议绑定固定ip
    callback_t _cb;
    bool _isrunning;
};